package de.se.ludoapp.activity.task;

import java.util.ArrayList;

import android.os.AsyncTask;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.R;
import de.se.ludoapp.activity.HighscoreActivity;
import de.se.ludoapp.response.HighscoreResponse;

/**
 * Task to get all request from other users for the game from the server.
 * 
 * @author Marlen Rotert
 * 
 */
public class HighscoreTask extends AsyncTask<String, Integer, String> {

	private LudoApplication ludoApp;
	private HighscoreActivity context;
	private ArrayList<String> highscore;

	public HighscoreTask(LudoApplication ludoApp, HighscoreActivity context) {
		super();
		this.ludoApp = ludoApp;
		this.context = context;
		this.highscore = null;
	}

	/**
	 * Get all request for game from Server.<br>
	 * This method is executed in a concurrent thread (asynchronous). Therefore
	 * you mustn't accessed on view elements!
	 */
	@Override
	protected String doInBackground(String... params) {
		/* Execute handleRequests */
		HighscoreResponse r = ludoApp.getLudoStub().getHighscore("Ludo");
		if (r.getReturnCode() == 0) {
			highscore = r.getHighscoreList();
		}
		return r.getMsg();
	}

	/**
	 * Show requests as list. <br>
	 * This method is invoked when the OpenGameTask is executed. You are only
	 * allowed here to access on view Elements (TextView and Buttons)!
	 */
	@Override
	protected void onPostExecute(String result) {
		if (highscore != null) {
			ListAdapter adapter = new ArrayAdapter(context,
					android.R.layout.simple_list_item_1, highscore);
			ListView listViewPlayerRequests = (ListView) context
					.findViewById(R.id.listHighscore);
			listViewPlayerRequests.setAdapter(adapter);
		} else {
			Toast.makeText(context, result, Toast.LENGTH_LONG).show();
		}
	}
}
